
public class ArrayStack implements IStack {
  
	private Object [ ] theArray;
	private int        topOfStack;
	    
    private static final int DEFAULT_CAPACITY = 10;
	
	
    public ArrayStack( ) {
        theArray = new Object[ DEFAULT_CAPACITY ];
        topOfStack = -1;
    }    
	
	public void stackPush(Object x) {
		 if( topOfStack + 1 == theArray.length )
	            doubleArray( );
	        theArray[ ++topOfStack ] = x;		
	}
	
	public Object stackTop() {
		 if( stackEmpty( ) )
	            throw new UnderflowException( "ArrayStack top" );
	        return theArray[ topOfStack ];
	}
	
	public Object stackPop() {
		Object lastItem = stackTop();
		
		if( stackEmpty( ) )
            throw new UnderflowException( "ArrayStack pop" );
        topOfStack--;
        
        return lastItem;
	}
	
	public boolean stackEmpty() {
		 return topOfStack == -1;
	}
	
	public void stackClear() {
		topOfStack = -1;		
	}
	
	public int stackSize() {
		return topOfStack + 1;
	}
	
	public void stackPrint() {
		StringBuilder builder = new StringBuilder();
		for (int i = topOfStack; i >= 0; i--) {
			builder.append(theArray[i]);
		}		
		
		System.out.println(builder.toString());
	}
	
	 private void doubleArray( ) {
	        Object [ ] newArray;
	        
	        newArray = new Object[ theArray.length * 2 ];
	        for( int i = 0; i < newArray.length; i++ )
	        {
	        	if (i < theArray.length)
	        		newArray[ i ] = theArray[ i ];
	        	else 
	        		newArray[ i ] = 0;
        	}
	        theArray = newArray;
	    }
    
}




